package com.shop.service.user;

import com.mysql.jdbc.StringUtils;
import com.shop.dao.BaseDao;
import com.shop.dao.shoppingcart.ShoppingCartDao;
import com.shop.dao.shoppingcart.ShoppingCartDaoImpl;
import com.shop.dao.user.LoginTicketDao;
import com.shop.dao.user.LoginTicketDaoImpl;
import com.shop.dao.user.UserDao;
import com.shop.dao.user.UserDaoImpl;
import com.shop.pajo.Book;
import com.shop.pajo.LoginTicket;
import com.shop.pajo.ShoppingCart;
import com.shop.pajo.User;
import com.shop.service.book.BookServiceImpl;
import com.shop.service.book.IBookService;
import com.shop.utils.CommunityUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

public class UserServiceImpl implements UserService{

    private ShoppingCartDao shoppingCartDao;

    private LoginTicketDao loginTicketDao;

    private IBookService bookService;

    private UserDao userDao;

    public UserServiceImpl() {
        shoppingCartDao = new ShoppingCartDaoImpl();
        loginTicketDao = new LoginTicketDaoImpl();
        userDao = new UserDaoImpl();
        bookService = new BookServiceImpl();
    }



    @Override
    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Connection connection = BaseDao.getConnection();
        Map<String, Object> map = new HashMap<>();

        //空值处理
        if(StringUtils.isNullOrEmpty(username)) {
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isNullOrEmpty(password)) {
            map.put("passwordMsg","密码不能为空");
            return map;
        }

        try {
            User selectUser = userDao.getUserByName(connection, username);
            if(selectUser == null) {
                map.put("usernameMsg", "该账号不存在");
                return map;
            }
            password = CommunityUtil.toMD5(password, selectUser.getSalt());

            if(!selectUser.getPassword().equals(password)) {
                map.put("passwordMsg", "该密码错误");
                return map;
            }

            //生成登录凭证
            LoginTicket loginTicket = new LoginTicket();
            loginTicket.setUserId(selectUser.getId());
            loginTicket.setTicket(CommunityUtil.generateUUID());
            loginTicket.setStatus(0);
            loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));

            //开启事务管理
            connection.setAutoCommit(false);
            loginTicketDao.addLoginTicket(connection, loginTicket);
            connection.commit();

            map.put("ticket",loginTicket.getTicket());

        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }

        return map;
    }

    @Override
    public LoginTicket getLoginTicketByTicket(String ticket) {
        Connection connection = BaseDao.getConnection();

        try {
            return loginTicketDao.getLoginTicketByTicket(connection, ticket);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public User getUserById(int id) {
        Connection connection = BaseDao.getConnection();

        try {
            return userDao.getUserById(connection, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUserByName(String username) {
        Connection connection = BaseDao.getConnection();
        try {
            return userDao.getUserByName(connection, username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int logout(String ticket) {
        Connection connection = BaseDao.getConnection();
        int update = 0;
        try {
            connection.setAutoCommit(false);
            update = loginTicketDao.updateStatus(connection, ticket, 1);
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }

        return update;
    }

    @Override
    public Map<String, Object> register(User user) {

        Map<String, Object> map = new HashMap<>();

        Connection connection = BaseDao.getConnection();

        if(user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        if(StringUtils.isNullOrEmpty(user.getName())) {
            map.put("usernameMsg","账号不能为空");
            return map;
        }
        if(StringUtils.isNullOrEmpty(user.getPassword())) {
            map.put("passwordMsg","密码不能为空");
            return map;
        }
        if(StringUtils.isNullOrEmpty(user.getEmail())) {
            map.put("emailMsg","邮箱不能为空");
            return map;
        }

        //验证账号
        User sus = null;
        try {
            sus = userDao.getUserByName(connection, user.getName());
            if(sus != null){
                map.put("usernameMsg","该账号已经存在了");
                return map;
            }
            sus = userDao.getUserByEmail(connection, user.getEmail());
            if(sus != null) {
                map.put("emailMsg","该邮箱已被注册");
                return map;
            }

            //注册用户
            user.setSalt(CommunityUtil.generateUUID().substring(0,5));
            user.setPassword(CommunityUtil.toMD5(user.getPassword(), user.getSalt()));

            connection.setAutoCommit(false);
            userDao.add(connection, user);
            connection.commit();

        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public Map<String, Object> addToCart(ShoppingCart shoppingCart) {
        Map<String, Object> map = new HashMap<>();
        Connection connection = BaseDao.getConnection();
        int addNum = 0;

        try {
            User user = userDao.getUserById(connection, shoppingCart.getUid());
            if(user == null) {
                map.put("error", "当前用户不存在无法添加购物车！");
                return map;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            ShoppingCart shoppingcart = shoppingCartDao.getShoppingCartById(connection, shoppingCart.getUid(), shoppingCart.getBid());
            if(shoppingcart != null) {
                map.put("error", "当前书已经被添加到购物车中！");
                return map;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            connection.setAutoCommit(false);
            addNum = shoppingCartDao.addToCart(connection, shoppingCart);
            connection.commit();
        } catch (SQLException e) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }

        return map;
    }

    @Override
    public List<Book> getCart(int uid) {
        Connection connection = BaseDao.getConnection();
        List<Book> bookList = new ArrayList<Book>();
        try {
            List<ShoppingCart> cartList = shoppingCartDao.getShoppingCartByUid(connection, uid);
            for (ShoppingCart cart : cartList) {
                bookList.add(bookService.getBookById(cart.getBid()));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return bookList;
    }

    @Override
    public int deleteCart(String bid) {
        Connection connection = BaseDao.getConnection();

        int deleteNum = 0;
        try {
            deleteNum = shoppingCartDao.deleteCartByBid(connection, bid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return deleteNum;
    }


}
